package webgamemaker.Editor;

import com.smartgwt.client.widgets.tab.Tab;

import webgamemaker.Common.MapData;
import webgamemaker.Common.TileSet;
import webgamemaker.Editor.MainPanel.MapTab;
import webgamemaker.Editor.MainPanel.TileSetEditorTab;
import webgamemaker.Editor.TileSetPanel.TileSetTab;

public class ProjectManager 
{
	private static ProjectManager instance;
	public ProjectData data;
	public ProjectTree projectTree;
	public TileSetPanel tilesetPanel;
	public MainPanel mainPanel;
	public Toolbar toolbar;
	
	public MapData currentMap;
	public int currentLayer;
	
	private ProjectManager()
	{
		data = new ProjectData();
	}
	
	public static ProjectManager getInstance()
	{
		if(instance == null)
			instance = new ProjectManager();
		return instance;
	}
	
	public void setProjectTree(ProjectTree projectTree)
	{
		this.projectTree = projectTree;
	}
	
	public void setTileSetPanel(TileSetPanel tilesetPanel)
	{
		this.tilesetPanel = tilesetPanel;
	}
	
	public void setMainPanel(MainPanel mainPanel)
	{
		this.mainPanel = mainPanel;
	}
	
	public void setToolbar(Toolbar toolbar)
	{
		this.toolbar = toolbar;
	}
	
	public void addMap(MapData map)
	{
		if(projectTree != null)
			projectTree.addMap(map);
		data.addMap(map);
	}
	public void addTileSet(MapData map, TileSet tileset)
	{
		if(projectTree != null)
			projectTree.addTileSet(map, tileset);
		map.addTileSet(tileset);
	}
	public void removeTileSet(MapData map, TileSet tileset)
	{
		if(projectTree != null)
			projectTree.removeTileSet(map, tileset);
		if(tilesetPanel != null)
		{
			TileSetTab tab = tilesetPanel.findTab(tileset);
			if(tab != null)
				tilesetPanel.removeTab(tab);
		}
		map.removeTileSet(tileset);
	}
	
	public void editTileSet(TileSet tileset)
	{
		if(mainPanel != null)
		{
			TileSetEditorTab tab = mainPanel.find(tileset);
			if(tab == null)
				tab = mainPanel.addTileSetEditor(tileset);
			mainPanel.selectTab(tab);
		}
	}
	
	public void selectMap(MapData map)
	{
		if(mainPanel != null)
		{
			MapTab mapTab = mainPanel.find(map);
			if(mapTab == null)
				mapTab = mainPanel.addMap(map);
			mainPanel.selectTab(mapTab);
			if(currentMap != map)
			{
				currentMap = map;
				for(Tab tab : tilesetPanel.getTabs())
					tilesetPanel.removeTab(tab);
				for(TileSet tileset : map.listTileSet)
					selectTileSet(map, tileset);
			}
			if(toolbar != null)
				toolbar.makeLayerButton(map.num_layer);
		}
	}
	
	public void selectTileSet(MapData map, TileSet tileset)
	{
		selectMap(map);
		if(tilesetPanel != null)
		{
			TileSetTab tab = tilesetPanel.findTab(tileset);
			if(tab == null)
				tab = tilesetPanel.addTileSet(tileset);
			tilesetPanel.selectTab(tab);
		}
	}
}
